Page({
  data: {
    form: {
      name: '',
      idCard: '',
      phone: '',
      address: '',
      startDate: '',
      idImages: [],
      proofImages: []
    },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '服务事项加载中...',

  // 显示全局加载
  showGlobalLoading(text = '服务事项加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },
    errors: {},
    showErrors: false,
    purposes: ['务工居住', '随迁居住', '学习居住', '其他'],
    purposeIndex: -1,
    agreed: true
  },

  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = (e.detail.value || '').trim()
    this.setData({ [`form.${field}`]: value })
  },

  onDateChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({ [`form.${field}`]: value })
  },

  onPurposeChange(e) {
    this.setData({ purposeIndex: Number(e.detail.value) })
  },

  onUploadId() {
    const that = this
    wx.chooseImage({
      count: 2,
      sizeType: ['compressed'],
      success(res) {
        that.setData({ 'form.idImages': res.tempFilePaths.slice(0, 2) })
      }
    })
  },

  onUploadProof() {
    const that = this
    wx.chooseImage({
      count: 6,
      sizeType: ['compressed'],
      success(res) {
        that.setData({ 'form.proofImages': res.tempFilePaths })
      }
    })
  },

  onAgreeChange(e) {
    const values = e.detail.value || []
    this.setData({ agreed: values.includes('agree') })
  },

  validate() {
    const { form, agreed } = this.data
    const errors = {}
    if (!form.name) errors.name = '请输入姓名'
    if (!form.idCard) errors.idCard = '请输入身份证号'
    if (!form.phone) errors.phone = '请输入联系电话'
    if (!form.address) errors.address = '请输入居住地址'
    if (!form.startDate) errors.startDate = '请选择居住起始日期'
    if (!form.idImages || form.idImages.length === 0) errors.idImages = '请上传身份证照片'
    if (!agreed) errors.agreed = '请勾选承诺声明'
    this.setData({ errors })
    return Object.keys(errors).length === 0
  },

  onSubmit() {
    this.setData({ showErrors: true })
    if (!this.validate()) {
      wx.showToast({ title: '请完善必填信息', icon: 'none' })
      return
    }
    // 此处仅做前端示例，实际应调用后端接口
    setTimeout(() => {
      wx.showToast({ title: '提交成功', icon: 'success' })
      setTimeout(() => wx.navigateBack({ delta: 1 }), 1200)
    }, 800)
  }
})


